package com.huangkailong.gitimgbed.jgit;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.util.FS;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author huangkl
 * @since 1.0.0
 */
public class MyJschConfigSessionFactory extends JschConfigSessionFactory {
    @Override
    protected void configure(OpenSshConfig.Host hc, Session session) {
        session.setConfig("StrictHostKeyChecking", "no");
    }

    @Override
    protected JSch createDefaultJSch(FS fs) throws JSchException {
        final JSch jsch = new JSch();
        configureJSch(jsch);
        knownHosts(jsch, fs);
        identities(jsch, fs);
        return jsch;
    }

    private static void knownHosts(JSch sch, FS fs) throws JSchException {
        final File home = fs.userHome();
        if (home == null)
            return;
        final File known_hosts = new File(new File(home, ".ssh"), "known_hosts");
        try (FileInputStream in = new FileInputStream(known_hosts)) {
            sch.setKnownHosts(in);
        } catch (FileNotFoundException none) {
            // Oh well. They don't have a known hosts in home.
        } catch (IOException err) {
            // Oh well. They don't have a known hosts in home.
        }
    }

    private static void identities(JSch sch, FS fs) {
        final File home = fs.userHome();
        if (home == null)
            return;
        final File sshdir = new File(home, ".ssh");
        if (sshdir.isDirectory()) {
            loadIdentity(sch, new File(sshdir, "identity"));
            loadIdentity(sch, new File(sshdir, "id_rsa"));
            loadIdentity(sch, new File(sshdir, "id_dsa"));
        }
    }

    private static void loadIdentity(JSch sch, File priv) {
        if (priv.isFile()) {
            try {
                sch.addIdentity(priv.getAbsolutePath());
            } catch (JSchException e) {
                // Instead, pretend the key doesn't exist.
            }
        }
    }
}
